<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\WechatUser;
use Illuminate\Support\Facades\Log;
use App\Models\UserToken;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;

class UserProfileController extends Controller
{
    /**
     * 显示用户个人信息
     * 
     * @param string $token
     * @return JsonResponse
     */
    public function show($token)
    {
        try {
            Log::info('开始获取用户信息', ['token' => $token]);

            if (empty($token)) {
                Log::warning('访问令牌为空');
                return response()->json([
                    'success' => false,
                    'message' => '未提供访问令牌',
                    'code' => 401
                ], 401);
            }

            // 查询token记录
            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', Carbon::now())
                ->first();

            if (!$userToken) {
                Log::warning('无效的访问令牌或已过期', [
                    'token' => $token,
                    'current_time' => Carbon::now()->format('Y-m-d H:i:s')
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '访问令牌无效或已过期',
                    'code' => 401
                ], 401);
            }

            Log::info('token验证通过，开始查询用户信息', [
                'wechat_user_id' => $userToken->wechat_user_id
            ]);

            // 根据token关联的wechat_user_id查询用户信息
            $user = WechatUser::select(['id', 'openid', 'nickname', 'created_at'])
                ->find($userToken->wechat_user_id);

            if (!$user) {
                Log::error('未找到对应的用户信息', [
                    'wechat_user_id' => $userToken->wechat_user_id
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '未找到用户信息',
                    'code' => 404
                ], 404);
            }

            Log::info('成功获取用户信息', [
                'user_id' => $user->id,
                'openid' => $user->openid
            ]);

            // 返回用户信息（修改字段名以匹配小程序端）
            return response()->json([
                'success' => true,
                'data' => [
                    'userId' => $user->id,
                    'openId' => $user->openid,
                    'nickName' => $user->nickname,
                    'registerTime' => $user->created_at->format('Y-m-d H:i:s'),
                    'memberLevel' => $user->member_level ?? 'normal', // 假设有会员等级字段，没有则返回默认值
                    'phone' => $user->phone ?? '' // 假设有手机号字段，没有则返回空字符串
                ],
                'code' => 200
            ]);

        } catch (\Exception $e) {
            Log::error('获取微信用户信息失败', [
                'token' => $token,
                'error_message' => $e->getMessage(),
                'error_trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '获取用户信息失败',
                'code' => 500
            ], 500);
        }
    }

    /**
     * 显示编辑用户信息的表单
     */
    public function edit($id)
    {
        try {
            $user = WechatUser::findOrFail($id);
            return view('wechat.users.profile.edit', compact('user'));
        } catch (\Exception $e) {
            Log::error('加载编辑用户页面失败：' . $e->getMessage());
            return back()->with('error', '加载编辑页面失败');
        }
    }

    /**
     * 更新用户信息
     * 
     * @param string $token
     * @param string $nickName
     * @return JsonResponse
     */
    public function update($token, $nickName)
    {
        try {
            Log::info('开始更新用户信息', [
                'token' => $token,
                'nickName' => $nickName
            ]);

            // 验证token
            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', Carbon::now())
                ->first();

            if (!$userToken) {
                Log::warning('无效的访问令牌或已过期', [
                    'token' => $token,
                    'current_time' => Carbon::now()->format('Y-m-d H:i:s')
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '访问令牌无效或已过期',
                    'code' => 401
                ], 401);
            }

            // 更新用户信息
            $user = WechatUser::find($userToken->wechat_user_id);
            if (!$user) {
                Log::error('未找到对应的用户信息', [
                    'wechat_user_id' => $userToken->wechat_user_id
                ]);
                return response()->json([
                    'success' => false,
                    'message' => '未找到用户信息',
                    'code' => 404
                ], 404);
            }

            $user->nickname = $nickName;
            $user->save();

            Log::info('用户信息更新成功', [
                'user_id' => $user->id,
                'nickname' => $nickName
            ]);

            return response()->json([
                'success' => true,
                'message' => '用户信息更新成功',
                'data' => [
                    'userId' => $user->id,
                    'openId' => $user->openid,
                    'nickName' => $user->nickname,
                    'registerTime' => $user->created_at->format('Y-m-d H:i:s'),
                    'memberLevel' => $user->member_level ?? 'normal',
                    'phone' => $user->phone ?? ''
                ],
                'code' => 200
            ]);

        } catch (\Exception $e) {
            Log::error('更新用户信息失败', [
                'token' => $token,
                'nickName' => $nickName,
                'error_message' => $e->getMessage(),
                'error_trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '更新用户信息失败',
                'code' => 500
            ], 500);
        }
    }

    /**
     * 更新用户头像
     */
    public function updateAvatar(Request $request, $id)
    {
        try {
            $validated = $request->validate([
                'avatar' => 'required|image|max:2048', // 最大2MB
            ]);

            $user = WechatUser::findOrFail($id);
            
            // 处理头像上传
            if ($request->hasFile('avatar')) {
                $path = $request->file('avatar')->store('avatars', 'public');
                $user->avatar = $path;
                $user->save();
            }

            return response()->json([
                'success' => true,
                'message' => '头像更新成功',
                'avatar_url' => asset('storage/' . $path)
            ]);
        } catch (\Exception $e) {
            Log::error('更新用户头像失败：' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '头像更新失败'
            ], 500);
        }
    }

    /**
     * 更新用户隐私设置
     */
    public function updatePrivacy(Request $request, $id)
    {
        try {
            $validated = $request->validate([
                'is_public_profile' => 'boolean',
                'allow_notifications' => 'boolean',
            ]);

            $user = WechatUser::findOrFail($id);
            $user->update($validated);

            return response()->json([
                'success' => true,
                'message' => '隐私设置更新成功'
            ]);
        } catch (\Exception $e) {
            Log::error('更新用户隐私设置失败：' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '更新隐私设置失败'
            ], 500);
        }
    }
} 